package com.zc.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.Observable;
import java.util.Observer;
import java.util.concurrent.ConcurrentHashMap;

/***
 * Web Socket 主题(被观察者)
 *
 * @author svili
 *
 */
public class WebSocketSubject extends Observable {

    /**
     * subject键值,对应不同的广播对象
     */
    private String principal;

    private WebSocketSubject(String principal) {
        this.principal = principal;
    }

    //观察者队列
    private static ConcurrentHashMap<String, WebSocketSubject> subjects = new ConcurrentHashMap<>();

    public String getPrincipal() {
        return principal;
    }

    public void setPrincipal(String principal) {
        this.principal = principal;
    }

    //根据type类型的不同,前台对应不同的操作.
    public void notify(String type, String data) {
        super.setChanged();
        JSONObject map = new JSONObject();
//        map.put("type", type);
//        map.put("data", data);
        map.put("type", "notice");
        map.put("data", data);
       String string = JSON.toJSONString(map);
        System.out.println(string);
        super.notifyObservers(string);
    }

    public static class Holder {


        public static WebSocketSubject getSubject(String principal) {
            if (subjects.containsKey(principal)) {
                return subjects.get(principal);
            }

            WebSocketSubject subject = new WebSocketSubject(principal);
            subjects.put(principal, subject);
            return subject;
        }
    }

    @Override
    public synchronized void deleteObserver(Observer o) {
        if(principal.equalsIgnoreCase("public")){
            return;
        }else{
            subjects.remove(principal);
            super.deleteObserver(o);
        }
    }
}
